"use strict"

const db = require("../lib/mysql")
const { success, fail } = require("../lib/result")

import showdown from "showdown"
const converter = new showdown.Converter()


const unescapeHTML = function(a) {
  return a
    .replace(/&nbsp;/g, " ")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&amp;/g, "&")
    .replace(/&quot;/g, '"')
    .replace(/&apos;/g, `'`)
}

/* 获取文章列表 */

const get = async function(ctx, next) {
  const query = ctx.request.query || ctx.request.body
  let articleId = ctx.params.id

  if (!query.page) {
    query.page = 1
  }
  if (!query.limit) {
    query.limit = 10
  }

  if (!(articleId > 0)) {
    let sql = ``,
      countSQL = ``

    if (query.label) {
      sql = `SELECT * FROM js_contents, js_users, js_relationships, js_metas WHERE js_metas.name = '${
        query.label
      }' && js_metas.mid = js_relationships.mid && js_relationships.cid = js_contents.cid && js_contents.authorId = js_users.uid LIMIT ${(query.page -
        1) *
        query.limit}, ${query.limit}`
      countSQL = `SELECT count(*) as count FROM js_contents, js_users, js_relationships, js_metas WHERE js_metas.name = '${query.label}' && js_metas.mid = js_relationships.mid && js_relationships.cid = js_contents.cid && js_contents.authorId = js_users.uid`
    } else if (query.search) {
      sql = `SELECT * FROM js_contents, js_users, js_relationships, js_metas WHERE (js_contents.title LIKE '%${
        query.search
      }%' || js_contents.text LIKE '%${
        query.search
      }%' || js_users.name LIKE '%${
        query.search
      }%') && js_contents.authorId = js_users.uid LIMIT ${(query.page - 1) *
        query.limit}, ${query.limit}`
      console.log(sql)
      countSQL = `SELECT count(*) as count FROM js_contents, js_users, js_relationships, js_metas WHERE (js_contents.title LIKE '%${query.search}%' || js_contents.text LIKE '%${query.search}%' || js_users.name LIKE '%${query.search}%') && js_contents.authorId = js_users.uid`
    } else if (query.collection) {
      if (!ctx.state.userInfo || !ctx.state.userInfo._id) {
        return fail(401, "获取收藏文章请先登录")
      }
      sql = `SELECT DISTINCT js_contents.cid as id, js_contents.title, js_contents.text as content, js_contents.created as create_time, js_contents.modified as update_time, js_users.name as user_name, js_users.uid as uid, js_collections.created as add_time FROM js_contents, js_users, js_collections WHERE js_collections.uid = ${
        ctx.state.userInfo._id
      } && js_contents.cid = js_collections.cid && js_contents.authorId = js_users.uid ORDER BY js_collections.created DESC LIMIT ${(query.page -
        1) *
        query.limit}, ${query.limit}`
      countSQL = `SELECT count (*) as count FROM js_collections WHERE js_collections.uid = ${ctx.state.userInfo._id}`
    } else {
      sql = `SELECT * FROM js_contents, js_users WHERE js_contents.authorId = js_users.uid LIMIT ${(query.page -
        1) *
        query.limit}, ${query.limit}`
      countSQL = `SELECT count(*) as count FROM js_contents, js_users WHERE js_contents.authorId = js_users.uid`
    }

    sql = sql.replace(
      "*",
      `DISTINCT js_contents.cid as id, js_contents.title, js_contents.text as content, js_contents.created as create_time, js_contents.modified as update_time, js_users.name as user_name, js_users.uid as uid`
    )

    countSQL = countSQL.replace("count(*)", "count(DISTINCT js_contents.cid)")
    const totalPage = await db.query(countSQL)
    let data = await db.query(sql),
      dataIncludeBrief = [],
      item
    data = Array.from(data)
    if (data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        item = data[i]
        if (item.content) {
          item.content = item.content.replace("<!--markdown-->", "")
          let brief
          if (item.content.includes("<!--more-->")) {
            brief = unescapeHTML(
              converter
                .makeHtml(item.content.split("<!--more-->")[0])
                .replace(/<[^<>]+>/g, "")
            )
          } else {
            brief = unescapeHTML(
              converter.makeHtml(item.content).replace(/<[^<>]+>/g, "")
            )
          }

          item.brief = brief

          item.label = await getLabelsByIDPrivate(item.id)
          dataIncludeBrief.push(item)
        }
      }
    }

    const labels = await db.query(`SELECT * FROM js_metas WHERE parent = 0`)

    return success({
      page: query.page,
      total_page:
        Math.ceil(
          JSON.parse(JSON.stringify(totalPage))[0]["count"] / query.limit
        ) || 1,
      limit: query.limit,
      list: dataIncludeBrief,
      label: labels
    })
  } else {
    const sql = `SELECT cid as id, title, text as content, js_contents.created as create_time, js_contents.modified as update_time, name as user_name, uid FROM js_contents, js_users WHERE js_contents.cid = ${articleId}`
    console.log(sql)
    const articleData = await db.query(sql)
    if ([...articleData].length > 0) {
      let article = articleData[0]
      if (article.content) {
        article.content = article.content.replace("<!--markdown-->", "")
      }
      article.labels = await getLabelsByIDPrivate(article.id)
      return success(article)
    } else {
      return fail(44, "文章不存在")
    }
  }
}

const getLabelsByIDPrivate = async function(articleId = 0) {
  try {
    if (articleId > 0) {
      const sql = `SELECT js_metas.name as label FROM js_metas, js_relationships WHERE js_relationships.mid = js_metas.mid && js_relationships.cid = ${articleId}`
      let res = await db.query(sql),
        labels = []
      res = Array.from(res)
      if (res.length > 0) {
        res.forEach(item => {
          if (item.label) {
            labels.push(item.label)
          }
        })
      }
      return labels
    }
  } catch (err) {
    return []
  }
}

const getLabelsList = async function(ctx, next) {
  try {
    const sql = `SELECT * FROM js_metas WHERE parent = 0`
    let res = await db.query(sql)
    res = Array.from(res)

    const childSQL = `SELECT * FROM js_metas WHERE 1`
    let childRes = await db.query(childSQL)
    childRes = Array.from(childRes)

    let dic = {}

    for (let a = 0; a < res.length; a++) {
      dic[res[a]["mid"]] = res[a]
      dic[res[a]["mid"]]["child"] = []
    }

    for (let i = 0; i < childRes.length; i++) {
      if (dic[childRes[i]["parent"]] && dic[childRes[i]["parent"]]["child"]) {
        dic[childRes[i]["parent"]]["child"].push(childRes[i])
      }
    }

    let resArr = []

    for (let key in dic) {
      resArr.push(dic[key])
    }

    return success(resArr)
  } catch (err) {
    return success([])
  }
}

module.exports = {
  get,
  getLabelsList
}
